import router from "@/router/index";

// 设置本地保存信息
export const setLocal = (key, value) => {
    if (key && value) {
        value = Object.assign(value, {
            local_expiry: Math.floor(new Date().getTime() / 1000) + 30 * 24 * 3600
        });
        localStorage.setItem(key, JSON.stringify(value));
    } else {
        return null;
    }
};
// 获取本地保存信息
export const getLocal = (key) => {
    const data = key ? localStorage.getItem(key) : "";
    //判断是否有结束时间字段
    if (data) {
        var tmpData = JSON.parse(data);
        if (tmpData && tmpData.local_expiry) {
            if (Math.floor(new Date().getTime() / 1000) > tmpData.local_expiry) {
                localStorage.removeItem(key);
                return null;
            }
        }
        return tmpData;
    } else {
        return null;
    }
};
// 删除本地保存信息
export const removeLocal = (key) => {
    key ? localStorage.removeItem(key) : "";
};

// 设置session信息
export const setSession = (key, value) => {
    if (key && value) sessionStorage.setItem(key, JSON.stringify(value));
};
// 获取session信息
export const getSession = (key) => {
    const data = key ? sessionStorage.getItem(key) : "";
    return data ? JSON.parse(data) : "";
};
// 删除session信息
export const removeSession = (key) => {
    key ? sessionStorage.removeItem(key) : "";
};

// 获取URL参数
const getUrl = (flag) => {
    if (flag === 1) {
        return location.href.split("?")[1];
    } else {
        const obj = [];
        const hrefs = location.href.split("?");
        if (hrefs[1]) {
            const keyValue = hrefs[1].split("&");
            if (keyValue) {
                for (let i = 0; i < keyValue.length; i++) {
                    const item = keyValue[i].split("=");
                    obj[item[0]] = item[1];
                }
            }
        }
        return obj;
    }
};

// 获取指定URL参数
const getUrlParam = (name) => {
    if (!name) return false;
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var result = window.location.search.substr(1).match(reg);
    return result ? decodeURIComponent(result[2]) : null;
};

//过滤手机号或身份证号或姓名位数为*号
const judegString = (val, flag = null) => {
    if (!val || !flag) return "";
    if (flag == 1) {
        //手机号隐藏*号
        const reg = /^(.{3}).*(.{4})$/;
        return val.replace(reg, "$1****$2");
    } else if (flag == 2) {
        //身份证号隐藏*号
        const reg = /^(.{4}).*(.{4})$/;
        return val.replace(reg, "$1****$2");
    } else if (flag == 3) {
        //姓名隐藏*号
        let name = "";
        if (val.length === 2) {
            name = val.substring(0, 1) + "*"; // 截取name 字符串截取第一个字符，
        } else if (val.length === 3) {
            name = val.substring(0, 1) + "*" + val.substring(2, 3); // 截取第一个和第三个字符
        } else if (val.length > 3) {
            name = val.substring(0, 1) + "**" + val.substring(val.length - 1, val.length); // 大于3个字只显示头尾中间用*号
        }
        return name;
    }
};

// 随机生成8位字母+数字(密码生成器)
const getStrings = (len) => {
    const chars = "ABCDEFGHIJKLMNOPQRSTUVWSYZabcdefghijklmnopqrstuvwsyz0123456789";
    const list = [];
    for (let i = 0; i < len; i++) {
        const val_1 = Math.round(Math.random() * 61);
        list.push(val_1);
    }

    let tmpStr = "";
    for (let n = 0; n < list.length; n++) {
        tmpStr += chars.charAt(list[n]);
    }
    const regNumber = new RegExp(`^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{${len}}$`);

    //最后判断是否符合要求（长度为8，由字母和数字组成），符合，将赋值到密码字段，不符合，重新调用该函数获取，只到符合为止
    if (regNumber.test(tmpStr)) {
        return tmpStr;
    } else {
        return getStrings(len);
    }
};

// 判断类型集合
const checkStr = (str, type) => {
    switch (type) {
        case "mobile": //手机号码
            return /^1[0-9]{10}$/.test(str);
        case "tel": //座机
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case "card": //身份证
            return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
        case "mobileCode": //6位数字验证码
            return /^[0-9]{6}$/.test(str);
        case "pwd": //密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
            return /^([a-zA-Z0-9_]){6,18}$/.test(str);
        case "payPwd": //支付密码 6位纯数字
            return /^[0-9]{6}$/.test(str);
        case "postal": //邮政编码
            return /[1-9]\d{5}(?!\d)/.test(str);
        case "QQ": //QQ号
            return /^[1-9][0-9]{4,9}$/.test(str);
        case "email": //邮箱
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case "money": //金额(小数点2位)
            return /^\d*(?:\.\d{0,2})?$/.test(str);
        case "URL": //网址
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str);
        case "IP": //IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
        case "date": //日期时间
            return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str);
        case "number": //数字
            return /^[0-9]$/.test(str);
        case "english": //英文
            return /^[a-zA-Z]+$/.test(str);
        case "chinese": //中文
            return /^[\\u4E00-\\u9FA5]+$/.test(str);
        case "lower": //小写
            return /^[a-z]+$/.test(str);
        case "upper": //大写
            return /^[A-Z]+$/.test(str);
        case "HTML": //HTML标记
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
        default:
            return true;
    }
};

//打开新页面:type:0,不储存在浏览器路由中;1,储存
const openPage = (url, data, type = 1) => {
    if (type == 1) {
        router.push({
            path: url,
            query: data
        });
    } else {
        router.replace({
            path: url,
            query: data
        });
    }
};

// 递归查询多维数组中key对应的元素值
const queryKey = (key, value, array) => {
    for (let i = 0; i < array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
        }
        if (array[i].children && array[i].children.length > 0) {
            const result = queryKey(key, value, array[i].children);
            if (result) {
                return result;
            }
        }
    }
    return null;
};

export default {
    checkStr,
    getUrl,
    getUrlParam,
    judegString,
    getStrings,
    openPage,
    queryKey
};
